<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Flow Control in Visual Basic</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Visual Basic, learn Visual Basic, language, flow control, If, Else If, While, For Each">
<meta name="description" content="This part of the Visual Basic tutorial covers flow control.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Flow control</h1>

<p>
In this part of the Visual Basic tutorial, we will talk about the flow control.
We will define several keywords that enable us to control the flow of the Visual Basic program. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>

<p>
In Visual Basic language there are several keywords that are used
to alter the flow of the program. When the program is run, the statements 
are executed from the top of the source file to the bottom. One by one. 
This flow can be altered by specific keywords. Statements can be executed
multiple times. Some statements are called conditional statements. They
are executed only if a specific condition is met. 
</p>

<h2>The If statement</h2>

<p>
The <code>If</code> statement has the following general form:
</p>

<pre>
If (expression)
    statement
End If
</pre>

<p>
The <code>If</code> keyword is used to check if an expression is true. If it is true, a
statement is then executed. The statement can be a single statement or a compound statement.
A compound statement consists of multiple statements enclosed by the If/End If block. 
</p>



<pre class="code">
Option Strict On


Module Example

    Dim num As Byte = 31

    Sub Main()

        If (num > 0)
            Console.WriteLine("num variable is positive")
        End If

    End Sub

End Module
</pre>

<p>
We have a num variable. It is assigned 31. The <code>If</code> keyword checks for a boolean
expression. The expression is put between square brackets. 31 > 0 is true, so the statement inside the
block is executed. 
</p>

<pre>
$ ./ifstatement.exe 
num variable is positive
</pre>

<p>
The condition is met and the message is written to the console. 
</p>


<pre class="code">
Option Strict On


Module Example

    Dim num As Byte = 31

    Sub Main()

        If (num > 0)
            Console.WriteLine("num variable is positive")
            Console.WriteLine("num variable equals {0}", num)
        End If

    End Sub

End Module

</pre>

<p>
More statements can be executed inside the block, created by
the <code>If</code>, <code>End If</code> keywords. 
</p>

<hr class="btm">

<p>
We can use the <code>Else</code> keyword to create a simple branch. 
If the expression inside the square brackets following the If keyword evaluates to 
false, the statement following the <code>Else</code> keyword is 
automatically executed. 
</p>

<pre class="code">
Option Strict On


Module Example

    Dim sex As String 

    Sub Main()

        sex = "female"

        If (sex = "male") 
          Console.WriteLine("It is a boy")
        Else 
          Console.WriteLine("It is a girl")
        End If

    End Sub

End Module
</pre>

<p>
We have a sex variable. It has "female" string. The boolean expression evaluates to false 
and we get "It is a girl" in the console.  
</p>

<pre>
$ ./branch.exe 
It is a girl
</pre>


<p>
We can create multiple branches using the <code>Else If</code> keyword.
The <code>Else If</code> keyword tests for another condition, if and only if 
the previous condition was not met. Note, that we can use multiple <code>Else If</code>
keywords in our tests.
</p>

<pre class="code">
Option Strict On


Module Example

    Dim a As Byte = 0

    Sub Main()

        If (a &lt; 0) 
          Console.WriteLine("a is negative")
        Else If (a = 0) 
          Console.WriteLine("a equals to zero")
        Else
          Console.WriteLine("a is a positive number")
        End If

    End Sub

End Module
</pre>

<p>
We have a numerical variable and we test it, if it is a negative number or positive or if it equals to
zero. The first expression evaluates to false. The second condition is met. The program
prints 'a equals to zero' to the console. The rest of the branch is skipped.  
</p>

<h2>Select statement</h2>

<p>
The <code>Select</code> statement is a selection control flow statement. 
It allows the value of a variable or expression to control the flow of program execution via a multi way branch.
It creates multiple branches in a simpler way than using the combination of <code>If</code>, 
<code>Else If</code> statements.
</p>

<p>
We have a variable or an expression. The <code>Select</code> keyword is used
to test a value from the variable or the expression against a list of values. 
The list of values is presented with the <code>Case</code> keyword. 
If the values match, the statement following the <code>Case</code> is executed. 
There is an optional <code>Case Else</code> statement. 
It is executed, if no other match is found.
</p>

<pre class="code">
Option Strict On


Module Example

    Dim domain As String

    Sub Main()

        domain = Console.ReadLine()
    
        Select domain
            Case "us"
                Console.WriteLine("United States")
            Case "de"
                Console.WriteLine("Germany")
            Case "sk"
                Console.WriteLine("Slovakia")
            Case "hu"
                Console.WriteLine("Hungary")
            Case Else
                Console.WriteLine("Unknown")
        End Select

    End Sub

End Module
</pre>

<p>
In our program, we have a <b>domain</b> variable. We read a value for the variable
from the command line. 
We use the <code>Case</code> statement to test for the value of
the variable. There are several options. If the value equals for example to "us" the
"United States" string is printed to the console. 
</p>

<pre>
$ ./selectcase.exe 
hu
Hungary
</pre>

<p>
We have entered "hu" string to the console and the program responded with "Hungary".
</p>

<hr class="btm">

<p>
The <code>Select</code> keyword enables to validate a range of 
numerical cases. 
</p>

<pre class="code">
Option Strict On


Module Example

    Dim age As Byte

    Sub Main()

        Try
            age = Console.ReadLine()
        Catch
            Console.WriteLine("Invalid value")
            End
        End Try
    
        Select age
            Case 0 To 21
                Console.WriteLine("Junior")
            Case 22 To 60
                Console.WriteLine("Adult")
            Case Else
                Console.WriteLine("Senior")
        End Select

    End Sub

End Module
</pre>

<p>
The preceding program uses range of numerical values to identify
an age group of a person.
</p>

<pre class="explanation">
Try
    age = Console.ReadLine()
Catch
    Console.WriteLine("Invalid value")
    End
End Try
</pre>

<p>
A value is read from the console. We can use only numerical
data. The <code>Try</code>, <code>Catch</code>,
<code>End Try</code> keywords are used for exception handling.
If an exception is thrown, the statements following the <code>Catch</code>
keyword are executed. The <code>End</code> statement terminates the program.
</p>

<pre class="explanation">
Case 0 To 21
    Console.WriteLine("Junior")
</pre>

<p>
Here we specify a range of values. If the value entered
by the user is in between 0 and 21, inclusive, then
the program prints "Junior" to the console. 
</p>

<pre>
$ ./agerange.exe 
43
Adult
</pre>

<p>
We have entered 43 and the program responded with the "Adult" string.
</p>


<h2>The While statement</h2>

<p>
The <code>While</code> statement is a control flow statement 
that allows code to be executed repeatedly based on a given boolean condition. 
</p>

<p>
This is the general form of the <code>While</code> loop:
</p>

<pre>
While (expression):
    statement
End While
</pre>

<p>
The <code>While</code> keyword executes the statements inside the
block enclosed by the <code>While</code>, <code>End While</code>
keywords. The statements are executed each time the expression is evaluated to 
true. 
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim i As Integer = 0
        Dim sum As Integer = 0

        While i &lt; 10

            i = i + 1
            sum += i
            
        End While

        Console.WriteLine(sum)

    End Sub

End Module
</pre>

<p>
In the code example, calculate the sum of values from a range of numbers.
</p>

<p>
The <code>While</code> loop has three parts. Initialization, 
testing and updating. Each execution
of the statement is called a cycle. 
</p>

<pre class="explanation">
Dim i As Integer = 0
</pre>

<p>
We initiate the i variable. It is used as a counter.
</p>

<pre class="explanation">
While i &lt; 10
...
End While
</pre>

<p>
The expression following the <code>While</code> keyword is the second phase, 
the testing. The statements in the body are executed, until the expression is evaluated 
to false. 
</p>

<pre class="explanation">
 i = i + 1
</pre>

<p>
The last, third phase of the <code>While</code> loop. 
The updating. We increment the counter. Note that
improper handling of the <code>While</code> loops may lead to endless cycles. 
</p>

<hr class="btm">

<p>
It is possible to run the statement at least once. Even
if the condition is not met. 
For this, we can use the <code>Do</code>, <code>Loop While</code>
keywords.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()

        Dim count As Integer = 0
        
        Do 
            Console.WriteLine(count)
        Loop While (count &lt;&gt; 0)

    End Sub

End Module
</pre>

<p>
First the iteration is executed and then the truth expression is evaluated. 
</p>


<h2>The For Next statements</h2>

<p>
When the number of cycles is know before the loop is initiated, 
we can use the <code>For Next</code> statements. 
In this construct we declare a counter variable, which is automatically
increased or decreased in value during each repetition of the loop.
</p>


<pre class="code">
Option Strict On


Module Example

    Sub Main()

        For i As Integer = 0 To 9
            Console.WriteLine(i)
        Next

    End Sub

End Module
</pre>

<p>
In this example, we print numbers 0..9 to the console. 
</p>

<pre class="explanation">
For i As Integer = 0 To 9
    Console.WriteLine(i)
Next
</pre>

<p>
We initiate the counter i to zero. The <code>Next</code> 
statement increases the counter by one until the counter equals
to 9.
</p>

<hr class="btm">

<p>
Visual Basic has an optional <code>Step</code> keyword. 
It controls how the counter variable is going to be increased or
decreased. 
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()

        For i As Integer = 9 To 0 Step -1
            Console.WriteLine(i) 
        Next

    End Sub

End Module
</pre>

<p>
In the above example, we print numbers 0..9 in
the reverse order. 
</p>

<pre class="explanation">
For i As Integer = 9 To 0 Step -1
    Console.WriteLine(i) 
Next
</pre>

<p>
The step may be a negative number too. We initiate the counter to
9. Each iteration the counter is decreased by the step value.
</p>

<h2>The For Each statement</h2>

<p>
The <code>For Each</code> construct simplifies 
traversing over collections of data. It has no explicit counter. 
The <code>For Each</code> statement goes through the
array or collection one by one and the current value is copied 
to a variable defined in the construct.
</p>

<pre class="code">
Option Strict On

Module Example

    Sub Main()
        
        Dim planets() As String = { "Mercury", "Venus", _
            "Earth", "Mars", "Jupiter", "Saturn", _
            "Uranus", "Neptune" }

        For Each planet As String In planets
            Console.WriteLine(planet)
        Next 
        
    End Sub

End Module
</pre>

<p>
In this example, we use the <code>For Each</code> statement to go
through an array of planets. 
</p>

<pre class="explanation">
For Each planet As String In planets
    Console.WriteLine(planet)
Next
</pre>

<p>
The usage of the <code>For Each</code> statement is straightforward.
The <b>planets</b> is the array, that we iterate through. The <b>planet</b> is the
temporary variable, that has the current value from the array. 
The <code>For Each</code> statement goes through all the planets 
and prints them to the console. 
</p>

<pre>
$ ./planets.exe 
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
</pre>

<p>
Running the above Visual Basic program gives this output.
</p>


<h2>The Exit, Continue statements</h2>

<p>
The <code>Exit</code> statement can be used to terminate 
block defined by <code>While</code>, <code>For</code>
or <code>Select</code> statements.
</p>

<pre class="code">
Option Strict On

Module Example

    Dim val As Integer

    Sub Main
        
        While (True)
        
            val = CType((30 * Rnd), Integer) + 1
            Console.Write(val.ToString &amp; " ")
            If (val = 22)
                Exit While
            End If        

        End While

        Console.Write(vbNewLine)

    End Sub

End Module
</pre>

<p>
We define an endless <code>While</code> loop. There is only one way to jump out
of a such loop. We must use the <code>Exit While</code> statement. 
We choose a random value from 1 to 30. We print the value. If the
value equals to 22, we finish the endless while loop. 
</p>

<pre>
$ ./exitstm.exe 
30 12 13 20 19 4 2 9 6 9 22 
</pre>

<p>
We might get something like this.
</p>

<hr class="btm">

<p>
The <code>Continue</code> statement is used to skip a
part of the loop and continue with the next iteration of the loop.
It can be used in combination with <code>Do</code>, 
<code>For</code> and <code>While</code>
statements. 
</p>

<p>
In the following example, we will print a list of numbers, 
that cannot be divided by 2 without a remainder. 
</p>

<pre class="code">
Option Strict On

Module Example

    Dim num As Integer = 0

    Sub Main()
        
        While (num &lt; 1000)
        
            num = num + 1

            If ((num Mod 2) = 0)
                Continue While
            End If        

            Console.Write(num.ToString() + " ") 

        End While

        Console.Write(vbNewLine)

    End Sub

End Module
</pre>

<p>
We iterate through numbers 1..999 with the <code>While</code> loop.
</p>

<pre class="explanation">
If ((num Mod 2) = 0)
    Continue While
End If  
</pre>

<p>
If the expression num Mod 2 returns 0, the number in question can be divided by 2.
The <code>Continue</code> statement is executed and the rest of the cycle is skipped.
In our case, the last statement of the loop is skipped and the number is not printed to the
console. The next iteration is started. 
</p>


<p>
In this part of the Visual Basic tutorial, we were talking 
about control flow structures. 
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>

<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified August 30, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

